<template>
  <div>
    <!-- 头部标签 -->
    <van-nav-bar fixed>
      <template #left>
        <!-- <img class="logo" src="../../assets/toutiao_logo.png" alt="" /> -->
        <img class="logo" :src="imgObj"/>
      </template>
      <template #right>
        <van-icon
        name="search"
        size="0.48rem"
        color="#fff"
        @click="$router.push({path: '/search'})"
        />
      </template>
    </van-nav-bar>
    <!-- v-model绑定当前选中的那一项 sticky粘性定位 -->
    <!-- 查文档得出,tab上绑定name属性,tabs上v-model可以获取name的值 -->
    <!-- @scroll="onScrollFn" -->
    <van-tabs
      v-model="channelId"
      animated
      sticky
      offset-top="1.226667rem"
      @scroll="onScrollFn"
      >
      <van-tab :title="obj.name" v-for="obj in userChannelsList" :key="obj.id" :name="obj.id">
        <van-pull-refresh
        v-model="isLoading"
        @refresh="pullDownRefresh"
        >
           <van-list
          v-model="loading"
          :finished="done"
          finished-text="我是有底线的···"
          @load="pullUpLoad"
          offset="80"
          :immediate-check="false"
        >
          <ArticleList :arr="articleList" @del_art="delArt"/>
        </van-list>
        </van-pull-refresh>
      </van-tab>

    </van-tabs>
    <!-- 编辑频道图标 -->
    <van-icon name="plus" size="0.45rem" class="moreChannels" @click="show = true"/>
    <!-- 频道管理组件 -->
    <van-popup v-model="show" class="edit_wrap">
       <!-- 弹出层的主体区域 -->
      <ChannelEdit
      :selectedChannelList="userChannelsList"
      @close-popup="show = false"
      @add-channel="addUserChannel"
      @del-channel="delUserChannel"
      @enter-channel="enterChannel"
      />
    </van-popup>

  </div>
</template>

<script>
import ArticleList from './articleList.vue'
import logoPng from '@/assets/images/logo.png'
import { getUserChannelsAPI, getArticleAPI, updataUserChannelListAPI } from '@/api/home'
import ChannelEdit from './ChannelEdit.vue'
// 缓存频道数据的大对象
const cacheObj = {}
export default {
  name: 'Home',
  components: {
    ArticleList,
    ChannelEdit
  },
  data () {
    return {
      show: false, // 控制弹出层(选择频道)显示与否
      isLoading: false,
      loading: false,
      done: false, // 上拉完成
      nextTime: undefined,
      imgObj: logoPng,
      channelId: 0,
      userChannelsList: [], // 发起请求获取的频道列表放在这里
      articleList: []
    }
  },
  // 记录切换页前滚动条位置
  beforeRouteLeave (to, from, next) {
    this.scrollY = window.scrollY
    next()
  },
  // 切回来时还原以前的滚动条位置
  activated () {
    window.scrollTo(0, this.scrollY)
  },
  // 获取频道列表
  async created () {
    const res = await getUserChannelsAPI()
    this.userChannelsList = res.data.channels
    this.getArticleList()
  },
  // 监测频道id变化,页面切换(tab切换)
  watch: {
    async channelId () {
      // this.loading = this.done = false
      // this.nextTime = undefined
      this.articleList = cacheObj[this.channelId] && cacheObj[this.channelId].list
        ? cacheObj[this.channelId].list : []
        // 切换频道,从缓存中结束页码开始,而不是每次从第一页开始
      this.nextTime = cacheObj[this.channelId] && cacheObj[this.channelId].nextTime
        ? cacheObj[this.channelId].nextTime : undefined
      await this.getArticleList()
      const scrollY = cacheObj[this.channelId] && cacheObj[this.channelId].scrollY
        ? cacheObj[this.channelId].scrollY : 0
      this.$nextTick(() => {
        window.scrollTo(0, scrollY)
      })
    }
  },
  methods: {
    // 封装获取对应频道的方法
    async getArticleList (pullUp = true) {
      /**
       * 几个情况不能走缓存
       * 1.上拉触底
       * 2.下拉刷新
       */
      if (cacheObj[this.channelId] && cacheObj[this.channelId].list && this.loading === false) {
        console.log('有缓存,无需请求')
        this.articleList = cacheObj[this.channelId].list
        return
      }
      const res = await getArticleAPI({
        channelId: this.channelId,
        timestamp: this.nextTime
      })
      // console.log(res)
      const { results, pre_timestamp: timestamp } = res.data
      // 发起请求取到数据后判断是否后续加载!
      if (timestamp == null || results.length < 10) {
        this.done = true
        this.$toast('没了!')
        return
      }
      this.nextTime = timestamp
      if (pullUp) {
      // 旧/新数据合并
        this.articleList = [...this.articleList, ...results]
        // 后续加载发起请求
        this.loading = false
      } else {
        setTimeout(() => {
        // 新旧数据合并,新的在前,旧的在后(或者新的将旧的完全覆盖,看需求)
          this.articleList = [...results, ...this.articleList]
          // 后续加载发起请求
          this.isLoading = false
        }, 1000)
      }
      cacheObj[this.channelId] = {}
      cacheObj[this.channelId].list = this.articleList
      cacheObj[this.channelId].nextTime = timestamp
    },
    // 频道文章列表滚动事件
    onScrollFn ({ scrollTop }) {
      cacheObj[this.channelId] = {}
      // 保存每个频道的滚动位置
      cacheObj[this.channelId].scrollY = scrollTop
    },
    // 弹层点击进入频道
    enterChannel (channelId) {
      this.channelId = channelId
      this.show = false
    },
    // 更新用户频道
    updataUserChannel () {
      // reduce 根据已有的数据汇总
      const arr = this.userChannelsList.reduce((sum, obj, idx) => {
        const item = {
          id: obj.id,
          seq: idx + 1
        }
        if (item.id !== 0) {
          sum.push(item)
        }
        return sum
      }, [])
      updataUserChannelListAPI({
        channels: arr
      })
    },
    // 添加频道
    addUserChannel (item) {
      // 1.同步到vue变量中
      this.userChannelsList.push(item)
      // 2.同步到后台
      this.updataUserChannel()
    },
    // 删除频道
    delUserChannel (i) {
      // 1.同步到vue变量中
      this.userChannelsList.splice(i, 1)
      // 2.同步到后台(注意这里的顺序)
      this.updataUserChannel()
    },
    // 删除文章
    async delArt (idx) {
      this.articleList.splice(idx, 1)
      if (this.articleList.length < 6) {
        const res = await getArticleAPI({
          channelId: this.channelId,
          timestamp: this.nextTime
        })
        // console.log(res)
        const { results, pre_timestamp: timestamp } = res.data
        // 发起请求取到数据后判断是否后续加载!
        if (timestamp == null || results.length < 10) {
          this.$toast('没有更多了...')
          return
        }
        // 旧/新数据合并}
        this.articleList = [...this.articleList, ...results]
        this.nextTime = timestamp
      }
    },
    // 上拉加载更多
    async pullUpLoad () {
      this.getArticleList(true)
    },
    // 下拉刷新更多
    async pullDownRefresh () {
      this.getArticleList(false)
    }
  }
}
</script>
<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content{
  padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 20px;
  background-color: #fff;
}
// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
